package ast;

import java.util.ArrayList;

import ast.FunctionSignature.SignatureType;
import symbol.astPreprocessContext;

public class BlockStatement extends Statement {
	public ArrayList<Statement> statements = new ArrayList<Statement>();
	
	public String classBelonged;
	
	public Boolean isConstructor;
	
	public void preprocess(AstItem father) {
		if (father instanceof FunctionSignature) {
			// 记录一下是不是构造器
			isConstructor = (((FunctionSignature) father).signatureType == SignatureType.CLASS_CONSTRUCTOR);
		}
		classBelonged = astPreprocessContext.getNowClass();
		for (Statement x : statements) {
			x.preprocess(this);
		}
	}
	
	public String toString() {
		String result = "{\n";
		if (classBelonged != null && isConstructor == true) {
			ArrayList<AstItem> stmts = astPreprocessContext.getClassAttrAssign(classBelonged);
			assert stmts != null;
			result += "struct " + classBelonged + "* this = (struct " + classBelonged + "*) malloc(sizeof(" + "struct " + classBelonged + "));\n"; 
			for (AstItem s : stmts) {
				result += s.toString() + "\n";
			}
		}
		for (Statement s : statements) {
			result += s.toString() + "\n";
		}
		if (classBelonged != null && isConstructor == true) {
			result += "return this;\n";
		}
		result += "}";
		return result;
	}
		
	@Override
	public String toJsonString() {
		String json = "{";
		json += "\"Type\": \"BlockStatement\",";
		json += "\"Statements\": [";
		for (AstItem astItem: statements) {
			json += astItem.toJsonString();
			json += ",";
		}
		json += "]";
		json += "}";
		return json;
	}
}
